package com.seo.controller.index;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seo.utils.code.CaptchaUtils;

/**
 * 验证码
 * 
 * @author shibeilei
 *
 */
@Controller
public class CodeController {

	@RequestMapping("/code/captcha-image")
	public void getKaptchaImage(String type, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		BufferedImage image = CaptchaUtils.generate();
		String code = CaptchaUtils.drawGraphic(image);
		code = code.toUpperCase();// 转成大写重要
		if (StringUtils.equals(type, "proxyUser")) {
			session.setAttribute(CaptchaUtils.CODE_PROXY_USER_SESSION, code);
		} else {
			session.setAttribute(CaptchaUtils.CODE_SESSION, code);
		}
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}

}
